<?php


namespace App\Domain\Auth\Services;


use App\Domain\Account\Dao\AccountDao;
use App\Domain\Account\Dao\AccountLogDao;
use App\Domain\Account\Services\AccountService;
use App\Exceptions\BadRequestException;
use App\Exceptions\ServiceException;
use App\Http\Services\System\SystemManager;
use App\Supports\Constant\ServiceConst;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

class AuthService
{
    /**
     * 登录
     * @param $params
     * @return array
     */
    public function Login($params)
    {
        $manager = new AccountService();
        $dao = new AccountDao();
        $accountModel = $dao->findByAccount($params['account']);
        if (empty($accountModel))
            throw new BadRequestException('账号不存在');
        if (!$manager->checkPassword($params['password'], $accountModel->salt, $accountModel->password))
            throw new BadRequestException('账号或密码错误');
        if ($accountModel->status == 0)
            throw new BadRequestException('账号已禁用');
        if (!$token = auth('api')->login($accountModel))
            throw new ServiceException('登录失败');
        //登录记录
        $dao->update($accountModel, [
            'last_login_time' => Carbon::now()->toDateTimeString(),
            'last_login_ip' => request()->getClientIp(),
        ]);
        $data = [
            'token' => $token,
            "name" => $accountModel->name,
            "role_id" => $accountModel->role_id,
        ];
        return $data;
    }



}
